const multer = require('koa-multer');
const fs = require('fs');
const moment = require('moment');
const server = {
    //本地缓存文件上传
    uploadloc: () => {
        let storage = multer.diskStorage({
            //文件保存路径
            destination: function (req, file, cb) {
                if (!fs.existsSync('./public/imgData/' + moment().format('YYYYMMDD'))) {
                    fs.mkdirSync('./public/imgData/' + moment().format('YYYYMMDD'))
                }
                cb(null, './public/imgData/' + moment().format('YYYYMMDD') + '/')
            },
            //修改文件名称
            filename: function (req, file, cb) {
                const fileFormat = (file.originalname).split(".");
                cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
            }
        });
        //加载配置
        let upload = multer({storage: storage});
        return upload;
    },
    //上传实时文章图片
    UploadNew: () => {
        let storage = multer.diskStorage({
            //文件保存路径
            destination: function (req, file, cb) {
                if (!fs.existsSync('./public/images/New')) {
                    fs.mkdirSync('./public/images/New')
                }
                cb(null, './public/images/New/')
            },
            //修改文件名称
            filename: function (req, file, cb) {
                const fileFormat = (file.originalname).split(".");
                cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
            }
        });
        //加载配置
        let upload = multer({storage: storage});
        return upload;
    },
    //删除实时文章图片
    RemoveNew:async (path) => {
        let result =await new Promise((resolve)=>{
            try{
                fs.unlinkSync(path);
                resolve({code:'1',msg:"文件删除成功"});
            }catch (e) {
                resolve({code:'0',msg:"文件删除失败"});
            }
        });
        return result;
    },
    //修改文件位置
    UpdateLoc:async (OldPath,Path)=>{
        let result=await new Promise((resolve,reject)=>{
            fs.rename(OldPath,Path,async (err)=>{
                if(err){
                    resolve({code:0,msg:err});
                    throw err
                }
                else {
                    resolve({code:1,msg:"文件移动成功"});
                }
            });
        });
        return result;
    }
};

module.exports = server;
